/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.UnauthorizedException;
import org.beetl.core.exception.BeetlException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.common.model.AjaxJson;
import com.common.util.ExceptionUtil;
import com.common.util.HtmlUtil;
import com.common.util.JsonUtils;

/**
 * 全局异常处理
 * 
 * @author limk
 * @date 2018年2月13日 上午9:22:34
 * @version 1.0
 */
@ControllerAdvice
public class AllRoundExceptionHandler implements HandlerExceptionResolver {

    private static final Logger LOGGER = LogManager.getLogger(AllRoundExceptionHandler.class);
    private static final String TEMPLATE_LOAD_ERROR = "TEMPLATE_LOAD_ERROR";
    
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
    	ModelAndView mv = new ModelAndView();
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if(handlerMethod != null) {
        	ResponseBody body = handlerMethod.getMethodAnnotation(ResponseBody.class);
        	// 判断有没有@ResponseBody的注解没有的话调用父方法
            if (body == null) {
                String exceptionMessage = ExceptionUtil.getExceptionMessage(ex);
                LOGGER.error("错误信息：" + exceptionMessage);
                Map<String, Object> model = new HashMap<String, Object>(16);
                model.put("exceptionMessage", exceptionMessage);
                model.put("ex", ex);

                // 根据不同错误转向不同页面
                if(ex instanceof UnauthorizedException) {
                	return new ModelAndView("/unauth", model);
                } else if (ex instanceof BusinessException) {
                    return new ModelAndView("error-business", model);
                } else if (ex instanceof ParameterException) {
                    return new ModelAndView("error-parameter", model);
                } else if (ex instanceof BeetlException){
                	if(TEMPLATE_LOAD_ERROR.equals(ex.getMessage())){
                		return new ModelAndView("404", model);
                	}
                }
            }
            HtmlUtil.writeJson(response, JsonUtils.toJSON(new AjaxJson(false, ex.getMessage())));
            LOGGER.debug("异常:" + ex.getMessage(), ex);
            return mv;
        } else {
        	return new ModelAndView("/404");
        }
    }

}
